__author__ = 'l4537'
#coding:utf-8
import pexpect
class Totalssh:
    def __init__(self,ip,root,password,cmd):
        self.ip = ip
        self.root = root
        self.password = password
        self.cmd = cmd
        self.ssh = pexpect.spawn('ssh %s@%s %s' % (self.root,self.ip,self.cmd))
    def login(self):
        i = self.ssh.expect([b'password:', b'continue connecting (yes/no)?'], timeout=5)
        if i == 0:
            self.ssh.sendline(self.password)
            self.ssh.sendline()
            return bytes.decode(self.ssh.read())
        elif i == 1:
            self.ssh.sendline('yes\n')
            self.ssh.expect(b'password: ')
            self.ssh.sendline(self.password)
            self.ssh.sendline()
            return bytes.decode(self.ssh.read())
    def logout(self):
        self.ssh.close()
import threading

# a = Totalssh("192.168.20.210","root","root")
# print(a.login())
#
def Start(ip,root,password,cmd):
    a = Totalssh(ip, root, password,cmd)
    b = a.login()
    print("\n-----",ip,"------\n",b)
    a.logout()
if __name__ == "__main__":
    list = {}
    while True:
        print("\n1：输入ip地址及账号及密码\n2:批量运行\n3:显示批量运行的IP")
        num = input("请选择:")
        if num == "1":
                ip = input("请输入IP：")
                root = input("请输入用户名：")
                password = input("请输入密码：")
                list[ip] = {}
                list[ip]["root"] = root
                list[ip]["password"] = password
        elif num =="2":
            while True:
                cmd = input("请输入命令，退出请输入q：")
                if cmd == "q":
                    break
                elif list == {}:
                    continue
                else:
                    for i in list:
                        t1 = threading.Thread(target=Start,args=(i,list[i]["root"],list[i]["password"],cmd,))
                        t1.start()

        elif num == "3":
            for i in list:
                print(i,"   ",list[i]["root"],"   ",list[i]["password"])